package com.myk.game.lib.rdm;

import android.util.Pair;

/**
 * 随机工具类
 */
public class RdmPropUtil {

    /**
     * 猜中了
     *
     * @param Numerator   分子
     * @param denominator 分母
     */
    public static boolean bingo(int Numerator, int denominator) {
        return Math.random() < 1d * Numerator / denominator;
    }

    /**
     * 猜中了
     */
    public static boolean bingo(double rate) {
        return Math.random() < rate;
    }

    /**
     * 加权随机，获取目标，俗称抽奖
     */
    @SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
    public static <T extends Wer> T lottery(Wer... wers) {
        int sumWeight = 0; //总权数
        for (Wer wei : wers) {
            sumWeight += wei.getWeight();
        }
        int addCount = 0; //当前域最大值
        double critical = Math.random() * sumWeight; //临界点
        for (Wer wei : wers) {
            addCount += wei.getWeight();
            if (addCount > critical) return (T) wei;
        }
        return null;
    }

    /**
     * 加权随机，获取目标，俗称抽奖
     */
    @SafeVarargs
    public static <T> T lottery(Pair<T, Integer>... wers) {
        int sumWeight = 0; //总权数
        for (Pair<T, Integer> wei : wers) {
            sumWeight += wei.second;
        }
        int addCount = 0; //当前域最大值
        double critical = Math.random() * sumWeight; //临界点
        for (Pair<T, Integer> wei : wers) {
            addCount += wei.second;
            if (addCount > critical) return wei.first;
        }
        return null;
    }

    /**
     * 加权随机,执行任务
     */
    public static void lotteryExecute(WerTask... wers) {
        int sumWeight = 0; //总权数
        for (WerTask wei : wers) {
            sumWeight += wei.getWeight();
        }
        int addCount = 0; //当前域最大值
        double critical = Math.random() * sumWeight; //临界点
        for (WerTask wei : wers) {
            addCount += wei.getWeight();
            if (addCount > critical) {
                wei.run();
                return;
            }
        }
    }

}
